class Solution {
public:
    ListNode *removeElements(ListNode *head, int val)
    {
        ListNode *pre = head;
        ListNode *p, *pHead;
        if(!pre){
            return NULL;
        }
        while(pre->val == val) {
            pre = pre->next;
            if(!pre) {
                return NULL;
            }
        }

        pHead = pre;
        while(pre) {
            if(pre->val == val) {
                p->next = pre->next;
                if(p) {
                    pre = p->next;
                } else {
                    return NULL;
                }
            } else {
                p = pre;
                pre = pre->next;
            }
        }
        return pHead;
    }
};